package cn.dduan.fool.lock.reentrant;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock
 * <p>
 * 是一种可重入、可中断、可公平锁、非公平锁
 * main方法没有释放锁，entrantLock方法也可获取锁，证明 ReentrantLock 可重入性
 *
 * @author dduan
 * @version 1.0
 * @date 2023/4/6
 */
public class MyReentrantLock {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            // 获取锁
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "-main方法中获取到了锁..");
                entrantLock();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
                System.out.println("main方法中释放到了锁..");
            }
        }).start();
    }


    private static void entrantLock() {
//        new Thread(() -> {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "-entrantLock方法中获取到了锁..");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
            System.out.println("entrantLock方法中释放了锁..");
        }
//        }).start();
    }
}
